/**
 * Created by kedong on 2017/7/29 0029.
 */

$(function () {
    // 分页大小
    var pageSize = 20;

    $('.tooltip-show').tooltip();
    /**
     * 关闭要素编辑面板
     */
    $("#edit_panel i").click(function (e) {
        $.publish("featurePanel:hide");
    });

    /*
     撤销
     */
    $('.J_undo').click(function () {
        $.publish("undo");
    });

    /*
     删除
     */
    $('#delete').click(function (e) {
        $.publish("feature:delete");
    });

    /*
     编辑要素属性
     */
    $('#edit_panel').on('change', 'input,select', function (e) {
        $.publish("input:change", {key: $(this).attr('name'), value: this.value});
    });

    $(".J_path").click(function (e) {

        $(this).siblings().removeClass("active");
        if (!$(this).hasClass('active')) {
            $(this).addClass("active");
            $("#path-list div.content").empty();
        } else {
            return;
        }
        var data_type = Number($(this).attr("data_type"));

        $('.list_title').each(function () {
            var path_type = $(this).attr("path_type");
            if (path_type == data_type) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
        switch (data_type) {
            case 1:
                // 用户轨迹
                $('#search_user_path_form').get(0).reset();
                getUserPath();
                break;
            case 2:
                // 系统已发布的轨迹
                getSysPath({isPublish: 1});
                break;
            case 3:
                // 待发布轨迹，当前用户的
                getSysPath({
                    isPublish: 0,
                    createId: userId
                });
                break;

        }

    });

    /**
     * 轨迹列表点击事件
     */
    $('#path-list').on("click", "a", function (e) {
        var type = $(this).parent().attr("path_type");
        var id = $(this).attr("id");
        var name = $(this).find('.path-name').text();

        if ($(this).hasClass('active')) {
            // 已选中，要取消
            $(this).removeClass("active");
            var featureArray = features.getArray();
            var featureId = type + "_" + id;
            for (var i = 0; i < featureArray.length; i++) {
                if (featureArray[i].getProperties().id == featureId) {
                    removeFeatures(featureArray[i]);
                    return;
                }
            }

        } else {
            // 未选中，要选中
            $(this).addClass("active");

            var geojson = $(this).attr("geojson");
            if (!!geojson && geojson != 'null') {
                addGeoJson(geojson, type, id, name);
                $.publish("select:on");
                return;
            }

            var gpx = $(this).attr("gpx");
            if (!!gpx && gpx != 'null') {
                addGpx(gpx, type, id, name);
                $.publish("select:on");
            }
        }
    });
    /**
     * 鼠标移入事件
     * 显示删除按钮
     */
    $('#path-list').on("mouseover", "a", function (e) {
        var type = $(this).parent().attr("path_type");
        if (type == 1)
            return;

        $(this).find("i").css({
            right: '12px'
        })
    });
    $('#path-list').on("mouseout", "a", function (e) {
        var type = $(this).parent().attr("path_type");
        if (type == 1)
            return;
        $(this).find("i").css({
            right: '-30px'
        })
    });
    /**
     * 删除系统轨迹
     */
    $('#path-list').on("click", "a i", function (e) {
        e.stopPropagation();
        var type = $(this).parents('#path-list').attr("path_type");
        if (type == 1)
            return;
        var _this_ = this;
        var id = $(this).parent().attr("id");
        var name = $(this).parent().find('.path-name').text();

        $.messager.confirm('提示:', '是否删除轨迹：' + name, function (e) {
            if (e) {
                $.post('deleteSysPath', {id: id}, function (data) {
                    if (data) {
                        $(_this_).parent().remove();
                    } else {
                        alert('删除失败')
                    }
                });
            }
        })

    });
    /**
     * 条件搜索用户轨迹
     */
    $('#search_user_path').click(function (e) {
        var formData = {
            startTime: $('#search_user_path_form').find('[name=startTime]').val(),
            endTime: $('#search_user_path_form').find('[name=endTime]').val(),
            mobile: $('[name=mobile]').val(),
            city: $('#city select').val() || '',
            systemType: $('[name=system_type]').val(),
            phoneModel: $('#search_user_path_form').find('[name=phone_model]').val()
        };

        console.log(formData);

        var defaultData = {
            type: 2,// 1、选点搜索附近的轨迹；2、条件搜索
            page: 1,
            rows: pageSize
        };
        $.extend(defaultData, formData);
        $.ajax({
            url: 'searchUser',
            type: 'get',
            data: defaultData,
            dataType: 'json',
            success: function (data) {
                $("#path-list div.content").empty();
                loadPathList({total: data.length, rows: data}, 1);
            }
        });
    });

    /**
     * 关闭轨迹列表面板
     */
    $('#path-list i').click(function (e) {
        pathListHide();
    });

    /**
     * 滚动加载更多
     */
    $("#path-list").scroll(function (e) {

        var viewH = $(this).height(),//可见高度
            contentH = $(this).get(0).scrollHeight,//内容高度
            scrollTop = $(this).scrollTop();//滚动高度
        if (scrollTop / (contentH - viewH) >= 0.95) { //到达底部100px时,加载新内容
            var target = $(this).find("div.content");
            var childrens = $(target).children('.list-group');
            var lastChild = childrens.get(childrens.length - 1);
            var total = $(lastChild).attr('total');
            var path_type = $(lastChild).attr("path_type");
            // 判断是不是最后一页
            if (isLastPage(total, childrens.length)) {
                console.log("没有更多数据了");
                return;
            }
            var page = childrens.length + 1;
            console.log("请求下一页数据,页数：" + page);
            if (path_type == 1) {
                // 用户轨迹列表
                getUserPath({page: page});
            } else if (path_type == 2) {
                // 系统轨迹列表
                getSysPath({page: page});
            }
        }

    });

    /**
     * 导入轨迹文件
     */
    $('#file').change(function (e) {
        var fileType = ['gpx', 'kml', 'geojson'];
        var files = this.files;
        for (var i = 0; i < files.length; i++) {
            var fileName = files[i].name;
            var suffix = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();
            if (fileType.indexOf(suffix) == -1) {
                this.value = '';
                alert(fileName + '不受支持的文件类型');
                return;
            }
        }

        for (var i = 0; i < files.length; i++) {
            var fileName = files[i].name;
            var suffix = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();
            var fr = new FileReader();
            switch (suffix) {
                case 'gpx':
                    fr.onloadend = function (e) {
                        addGpx(e.target.result);
                    };
                    break;
                case 'kml':
                    fr.onloadend = function (e) {
                        var kmlFormat = new ol.format.KML();
                        var kml = kmlFormat.readFeatures(e.target.result, {
                            dataProjection: 'EPSG:4326'
                        });
                        addFeatures(kml,null,true);
                        var geometry = kml[0].getGeometry();
                        var coordinate = geometry.getFirstCoordinate();
                        center(coordinate);
                        // view.fit(kml[0].getGeometry(), {padding: [170, 50, 30, 150], constrainResolution: false});
                    };
                    break;
                case 'geojson':
                    fr.onloadend = function (e) {
                        var geoJsonFeatures = (new ol.format.GeoJSON()).readFeatures(e.target.result);
                        addFeatures(geoJsonFeatures);
                        var geometry = geoJsonFeatures[0].getGeometry();
                        var coordinate = geometry.getFirstCoordinate();
                        center(coordinate);
                    };
                    break;
            }
            fr.readAsText(files[i]);
        }
    });
    function elastic(t) {
        return Math.pow(2, -10 * t) * Math.sin((t - 0.075) * (2 * Math.PI) / 0.3) + 1;
    }

    function center(coordinate) {
        if (!!coordinate[0] && !!coordinate[1]) {
            view.animate({
                duration: 700,
                easing: elastic,
                center: coordinate
            });
        }
    }

    function isLastPage(total, currentPage) {
        var pageCount = Math.ceil(total / pageSize);
        return currentPage == pageCount;
    }

    /**
     * 获取系统轨迹
     * @param data
     */
    function getSysPath(data) {
        var defaultData = {
            page: 1,
            rows: pageSize
        };
        $.extend(defaultData, data);
        $.ajax({
            url: 'getSysPath',
            type: 'POST',
            data: defaultData,
            dataType: 'json',
            success: function (data) {
                loadPathList(data, 2);
            }
        });
    }

    /**
     * 获取用户轨迹
     * @param data
     */
    function getUserPath(data) {
        var defaultData = {
            page: 1,
            rows: pageSize
        };
        $.extend(defaultData, data);
        $.ajax({
            url: 'getUserPath',
            type: 'POST',
            data: defaultData,
            dataType: 'json',
            success: function (data) {
                loadPathList(data, 1);
            }
        });
    }


    /**
     * 显示要素编辑面板
     */
    var isReady = false;

    function pathListShow() {
        if (!isReady) {
            /**
             * 初始化省市级联菜单
             */
            isReady = getProvince();
        }
        $('#path-list').animate({
            right: '8px'
        }, 'fast');
    }

    /**
     * 关闭要素编辑面板
     */
    function pathListHide() {
        $('#path-list').animate({right: '-358px'}, 'fast', function () {
            $('#path-list').find('div.content').empty();
        });
        $('.J_path').removeClass('active');
    }

    /**
     * 加载GPX格式轨迹
     * @param gpxStr
     * @param type 1:用户轨迹；2:系统轨迹
     * @param id
     * @param name
     */
    function addGpx(gpxStr, type, id, name) {
        var gpxId = type + "_" + id;
        var features = featureOverlay.getSource().getFeatures();
        for (var i = 0; i < features.length; i++) {
            if (features[i].getProperties().id == gpxId)
                return;
        }
        var gpxFormat = new ol.format.GPX();
        var gpx = gpxFormat.readFeatures(gpxStr, {
            dataProjection: 'EPSG:4326'
        });
        if (!!gpxId) {
            gpx[0].setProperties({
                id: gpxId,
                name: name
            })
        }
        addFeatures(gpx,type);
        var geometry = gpx[0].getGeometry();
        var coordinate = geometry.getFirstCoordinate();
        center(coordinate);
        $.publish('select:on');
    }

    /**
     *
     * @param geojson
     * @param type 1:用户轨迹；2:系统轨迹
     * @param id
     * @param name
     */
    function addGeoJson(geojson, type, id, name) {
        var geojsonId = type + "_" + id;
        var features = featureOverlay.getSource().getFeatures();
        for (var i = 0; i < features.length; i++) {
            if (features[i].getProperties().id == geojsonId)
                return;
        }
        var geojsonFormat = new ol.format.GeoJSON();
        var geoJsonFeatures = geojsonFormat.readFeatures(geojson);

        if (!!geojsonId) {
            geoJsonFeatures[0].setProperties({
                id: geojsonId,
                name: name
            })
        }

        addFeatures(geoJsonFeatures,type);
        var geometry = geoJsonFeatures[0].getGeometry();
        var coordinate = geometry.getFirstCoordinate();
        center(coordinate);
        $.publish('select:on');
    }


    /**
     *
     * @param listData
     * @param type 1:用户轨迹；2:系统轨迹
     */
    function loadPathList(listData, type) {
        type == 2 ? $('.search').hide() : $('.search').show();
        if (listData.total > 0) {
            var rows = listData.rows.map(function (item) {
                // 轨迹持续时间（单位：秒）
                item.time = timeformatter(item.time);
                item.kilometre = item.kilometre / 1000;
                return item;
            });

            var data = {
                type: type,
                total: listData.total,
                list: rows
            };
            var arrText = doT.template($("#path").text());
            $('.nodata').hide();

            $("#path-list div.content").append(arrText(data));
        } else {
            var nodata = ' <h3 class="nodata">暂无数据</h3>';
            $('#path-list .content').html(nodata);
        }
        pathListShow();
    }

    /**
     *
     * @param second
     * @returns {string}
     */
    function timeformatter(second) {
        if(second == undefined){
            return '';
        }
        // 分
        var min = second / 60;
        var hour = min / 60;
        var secendStr = second % 60;
        var minStr = Math.floor(min) % 60;
        var hourStr = Math.floor(hour);
        secendStr = secendStr < 10 ? '0' + secendStr : secendStr;
        minStr = minStr < 10 ? '0' + minStr : minStr;
        hourStr = hourStr < 10 ? '0' + hourStr : hourStr;

        return hourStr + ":" + minStr + ":" + secendStr;
    }
    window.loadGpx = addGpx;
    window.loadGeoJson = addGeoJson;
});
